package com.example.project;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.project.db.DBHelper;
import com.example.project.dto.ListnoCategoryDto;
import com.example.project.history.History;

/**
 * @author Jang
 *
 */
public class MultiPaneWidth extends Activity {

	private DBHelper mDbManager;
	private static boolean isfirst = true;// 처음에만 splash 뜨라고
	private java.util.ArrayList<ListnoCategoryDto> arr_list;
	private Cursor cursor;
	private QueryListFragment newFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		History.ishistory = false;
		setContentView(R.layout.activity_main);
		if (isfirst) {
			startActivity(new Intent(this, SplashActivity.class));
			isfirst = false;// 처음 실행되는거 아니라고
		}
		getActionBar().setHomeButtonEnabled(true);
		mDbManager = DBHelper.getInstance(this);
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.actionbarmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		switch (item.getItemId()) {
		case R.id.queryadd:
			intent = new Intent(this, QueryAddActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case R.id.myhistory:
			intent = new Intent(this, History.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		case android.R.id.home:
			intent = new Intent(this, MultiPaneWidth.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}
		return false;
	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.btnsearch:
			EditText searchkey = (EditText) findViewById(R.id.searchkey);
			arr_list = new java.util.ArrayList<ListnoCategoryDto>();
			newFragment = (QueryListFragment) getFragmentManager()
					.findFragmentById(R.id.querylist);

			findName(searchkey.getText().toString());// 한글 자음/완성형 글자로 된 카테고리 검색

			cursor = mDbManager.search(searchkey.getText().toString());// 쿼리문 검색
			if (cursor.moveToFirst()) {
				int n_list_no = cursor.getColumnIndex("list_no");
				int n_category = cursor.getColumnIndex("category");
				do {
					String list_no = cursor.getString(n_list_no);
					String category = cursor.getString(n_category);
					ListnoCategoryDto dto = new ListnoCategoryDto(list_no,
							category);
					arr_list.add(dto);
					Log.d("print", dto.toString());
				} while (cursor.moveToNext());
			}// 수정해야할 부분 -- 카테고리가 중복될 가능성이 있음(카테고리+쿼리문에서)
			if (arr_list.size() > 0) {
				newFragment.setArr_list(arr_list);
			} else {
				Toast.makeText(this, "검색 결과 없지롱", Toast.LENGTH_LONG).show();
			}
			// FM에서 포함된 프레그먼트 가져와서 거기다가 set
			cursor.close();
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			new AlertDialog.Builder(this)
					.setIcon(android.R.drawable.ic_dialog_alert).setTitle("종료")
					.setMessage("종료하시겠습니까?")
					.setPositiveButton("확인", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							moveTaskToBack(true);
							isfirst = true;
							finish();
						}
					}).setNegativeButton("취소", null).show();
			break;
		}
		return true;
	}

	// 초성 찾기
	final static char[] chosungWord = { 0x3131, 0x3132, 0x3134, 0x3137, 0x3138,
			0x3139, 0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147, 0x3148,
			0x3149, 0x314a, 0x314b, 0x314c, 0x314d, 0x314e };

	/**
	 * @param str
	 * @return conslist
	 * TODO
	 * String을 받아서 자음만으로 된 부분의 index를 리턴
	 */
	public ArrayList<Integer> getConsonantIndex(String str){
		ArrayList<Integer> conslist = new ArrayList<Integer>();
		
		for(int i = 0; i<str.length(); i++){
			char ch = str.charAt(i);
			if (ch != ' ') {
				if (ch >= 0x3131 && ch <= 0x314e) {
					conslist.add(i);
				}
			}
		}
		
		return conslist;
	}
	
	/**
	 * @param str
	 * @param conslist
	 * @return resultString
	 * TODO
	 * str의 index와 conslist의 값이 같은 부분의 값을 초성으로 변경
	 */
	public String mixConsonant(String str, ArrayList<Integer> conslist) {
		int chosungNum, tempNum, index;
		String resultString = "";

		int j=0;
		char ch = 0;
		for(int i=0;i<conslist.size(); i++){
			index = conslist.get(i);
			Log.d("conslist", "index = conslist.get(i);" + index);
			while(j!=index){
				ch = str.charAt(j);
				resultString += ch;
				j++;
				Log.d("conslist", "resultString += ch;" + resultString + "  제이의 변화: " + j);
			}
			if(j==index){
				ch = str.charAt(index);
				Log.d("conslist", "자음으로바꿀: " + ch);
				if (ch != ' ') {
					if (ch >= 0xAC00 && ch <= 0xD7A3) {
						tempNum = ch - 0xAC00;
						chosungNum = tempNum / (21 * 28);
						resultString += chosungWord[chosungNum];
						j++;
						Log.d("conslist", "resultString += chosungWord[chosungNum];" + resultString + "  제이의 변화: " + j);
					}
				}
			}
		}
		
		if(str.length()>conslist.get(conslist.size()-1)){
			j = conslist.get(conslist.size()-1)+1;
			while(j<str.length()){
				ch = str.charAt(j);
				resultString += ch;
				j++;
				Log.d("conslist", "str.length()~~resultString += ch;" + resultString + "제이의 변화: " + j);
			}
		}
			
		return resultString;
	}
	
	public String hangulToOnlyChosung(String s) {
		int chosungNum, tempNum;
		String resultString = "";

		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if (ch != ' ') {
				if (ch >= 0xAC00 && ch <= 0xD7A3) {
					tempNum = ch - 0xAC00;
					chosungNum = tempNum / (21 * 28);

					resultString += chosungWord[chosungNum];
				} else {
					resultString += ch;
				}
			}
		}
		return resultString;
	}

	public void findName(String findString) {
		java.util.ArrayList<ListnoCategoryDto> origin = new java.util.ArrayList<ListnoCategoryDto>();
		origin = newFragment.getFirstlist();

		ArrayList<Integer> conslist = getConsonantIndex(findString);
		String categorysub="";
		
		if(conslist.size()>0){
			String forindex = findString.substring(0, conslist.get(0));
			Log.d("conslist", forindex);
			
			if(conslist.size()==findString.length()){
				//only 자음
				Log.d("conslist", conslist.size()+" conslist");
				Log.d("conslist", findString.length()+"findString");
				String onlyChosungString = hangulToOnlyChosung(findString);
				for (int j = 0; j < origin.size(); j++) {
					String onlyChosungNameString = hangulToOnlyChosung(origin
							.get(j).getCategory());
					if (onlyChosungNameString.contains(onlyChosungString)) {
						arr_list.add(origin.get(j));
					}
				}
			}else{
				for (int i = 0; i < origin.size(); i++) {
					int findindex = origin.get(i).getCategory().indexOf(forindex);
					if(findindex!=-1){
						Log.d("conslist", "findindex" + findindex);
						if((findindex+findString.length())<=origin.get(i).getCategory().length()){
							Log.d("conslist", "findindex+findString.length()" + findindex+findString.length());
							//찾아 볼만큼의 길이가 된다
							categorysub=origin.get(i).getCategory().substring(findindex, findindex+findString.length());
							Log.d("conslist", "mixConsonant에 들어가는 인자:" + categorysub);
							categorysub = mixConsonant(categorysub, conslist);
							
							if(findString.equals(categorysub)){
								arr_list.add(origin.get(i));
							}
						}
					}
				}
			}
		}else{
			for (int i = 0; i < origin.size(); i++) {
				if(origin.get(i).getCategory().contains(findString)){
					arr_list.add(origin.get(i));
				}
			}
		}
		
		
		/*if (findString.length() > 0) {
			String onlyChosungString = hangulToOnlyChosung(findString);

			for (int i = 0; i < origin.size(); i++) {
				String onlyChosungNameString = hangulToOnlyChosung(origin
						.get(i).getCategory());
				if (onlyChosungNameString.matches(onlyChosungString + ".*")) {
					arr_list.add(origin.get(i));
				}
			}
		}*/
	}
}
